package vn.gq.app4vn.doctruyen;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONTokener;

import vn.gq.app4vn.doctruyen.BuildConfig;
import vn.gq.tym.utils.ClientIO;
import vn.gq.tym.utils.DataType;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;


public class AdClient extends AsyncTask<String, Integer, Object>{

	private Context context;
	private HttpURLConnection httpURLConnection = null;
	private DataType dataType = DataType.JSON;
	
	
	public AdClient(Context context) {
		this.context = context;
	}
	
	private AdClientListener listener = null;
	
	public void load(String url, AdClientListener listener) {
		this.listener = listener;
		execute(url);
	}
	
	@Override
	protected Object doInBackground(String... urls) {
		disableConnectionReuseIfNecessary();
		InputStream is;
		String url = urls[0];
		if (BuildConfig.DEBUG) {
			Log.e(getClass().getSimpleName(), "---load url: "+String.valueOf(url));
		}
		try {
			httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
			httpURLConnection.setRequestMethod("GET");
			int code = httpURLConnection.getResponseCode();
			if (code == HttpStatus.SC_OK) {
				String encoding = httpURLConnection.getHeaderField("Content-Encoding");
				if (encoding != null) {
					if (encoding.contains("gzip")) {
						
					}
				}
				is = httpURLConnection.getInputStream();
				String raw = ClientIO.convertStreamToString(is, null);
				switch (dataType) {
					case JSON:
						return new JSONTokener(raw).nextValue();
					default:
						break;
				}
				return raw;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			httpURLConnection.disconnect();
		}
		
		return null;
	}

	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if (listener != null) {
			listener.onDone(result);
		}
	}

	public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }
	
	public interface AdClientListener {
		void onDone(Object result);
	}
}
